package com.reggie.controller.admin;


import com.google.j2objc.annotations.AutoreleasePool;
import com.reggie.constant.JwtClaimsConstant;
import com.reggie.constant.MessageConstant;
import com.reggie.constant.StatusConstant;
import com.reggie.dto.EmployeeDTO;
import com.reggie.dto.EmployeeLoginDTO;
import com.reggie.dto.EmployeePageQueryDTO;
import com.reggie.dto.PasswordEditDTO;
import com.reggie.entity.Employee;
import com.reggie.exception.AccountLockedException;
import com.reggie.exception.AccountNotFoundException;
import com.reggie.exception.PasswordErrorException;
import com.reggie.properties.JwtProperties;
import com.reggie.result.PageResult;
import com.reggie.result.R;
import com.reggie.service.EmployeeService;
import com.reggie.utils.JwtUtil;
import com.reggie.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;


//webController操作
@RestController
@Slf4j
@RequestMapping("/admin/employee")
/**
 * @Api(tags="员工相关接口") 这个Api用在类上  用来表示这个类的说明
 */
@Api(tags="员工相关接口")
public class EmployeeController {
    @Autowired   //生成业务逻辑对象
    private EmployeeService employeeService;
    @Autowired  //生成Jwt令牌对象
    private JwtProperties jwtProperties;

    /**
     *
     * @param employeeLoginDTO  用户登录提交的用户名和密码
     * @return
     */
    //post请求方法  员工登录
    @PostMapping("/login")
    /**  Swagger  Api说明
     * ApiOperation 用在方法上 ,说明方法的用途作用
     */
    @ApiOperation("员工登录")
    public R<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO){
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        Employee employee = employeeService.getByUsername(username);
        //获取到的用户信息对象为空 处理异常
        if (employee==null){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);

        }
        //为0  表示账户禁用 处理异常
        if(employee.getStatus() == StatusConstant.DISABLE){
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);

        }
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        //判断md5处理后的密码与数据库md5密码如果不一致 抛出异常
        if(!pwd.equals(employee.getPassword())){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);

        }
        HashMap<String, Object> claims = new HashMap<>();
        //设置Jwt中的有效载荷部分的数据,通常是用户的身份表示
        claims.put(JwtClaimsConstant.EMP_ID,employee.getId());
        //创建jwt的令牌token
     /*   String token = JwtUtil.createJWT("itcast", 1000 * 60 * 60, claims);
       */
        String token = JwtUtil.createJWT(
                //秘钥
                jwtProperties.getAdminSecretKey(),
                //存活时间
                jwtProperties.getAdminTtl(),
                //载荷
                claims
        );
        //响应前端的VO数据封装
        EmployeeLoginVO employeeLoginVO=EmployeeLoginVO.builder()
                .id(employee.getId())
                .name(employee.getName())
                .userName(employee.getUsername())
                .token(token)
                .build();
        //将封装的Vo数据响应给浏览器解析
        return R.success(employeeLoginVO);
    }

    /**  Api注释
     * ApiImplicitParams  用来定义多个形参的说明 以及是否必须的参数设置 与ApiImplicitParam  配合使用
     * @param i
     * @param j
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name="i",value = "参数一",required = true),
            @ApiImplicitParam(name="j",value = "参数二",required = false)
    })
    //测试方法1
    @GetMapping("/testJwt1")
    public R<String> testJwt1(int i,int j){
        return R.success("jwt test");
    }
    //测试方法2
    @GetMapping("/testJwt")
    public R<String> testJwt(){
        return R.success("jwt test");
    }

    /**
     * 退出登录,这里直接编写即可  前端会自行处理
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("退出登录")
    public R<String> logout(){
        return R.success();
    }


    @PostMapping
    @ApiOperation("新增员工信息")
    public R<String> save(@RequestBody EmployeeDTO employeeDTO){
        employeeService.save(employeeDTO);
        return R.success();

    }


    @GetMapping("/page")
    @ApiOperation("员工分页查询")
    public R<PageResult> page(EmployeePageQueryDTO employeePageQueryDTO){
        PageResult pageResult = employeeService.pageQuery(employeePageQueryDTO);
        return R.success(pageResult);
    }


    @PostMapping("/status/{status}")
    @ApiOperation("启用禁用员工账号")
    public R<String> startOrStop(@PathVariable Integer status,Long id){
        log.info("启用禁用员工账号");
        employeeService.startOrStop(status,id);
        return R.success();
    }



    @GetMapping("/{id}")
    @ApiOperation("根据员工id查询员工信息")
    public R<Employee> getById(@PathVariable("id") Long id){
        return R.success(employeeService.getById(id));
    }

    @PutMapping
    @ApiOperation("修改员工信息")
    public R<String> update(@RequestBody EmployeeDTO employeeDTO){
        employeeService.update(employeeDTO);
        return R.success();

    }

    /**
     * 修改当前用户的密码
     * @param passwordEditDTO
     * @return
     */
     @PutMapping("/editPassword")
     @ApiOperation("修改密码 ")
    public R<String> updatePassword(@RequestBody PasswordEditDTO passwordEditDTO){
         employeeService.updatePassword(passwordEditDTO);
         return R.success();

    }




}
